{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2807e70",
   "metadata": {},
   "outputs": [],
   "source": [
    "import altair as alt\n",
    "import pandas as pd\n",
    "import panel as pn\n",
    "\n",
    "pn.extension('vega', template='fast')\n",
    "\n",
    "pn.state.template.title = \"Altair Brushing Example\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc2aa754",
   "metadata": {},
   "source": [
    "This example demonstrates how to leverage the brushing/linked-selections support in the Vega pane to update a table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9327af65",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_json(\"https://raw.githubusercontent.com/vega/vega/master/docs/data/penguins.json\")\n",
    "\n",
    "brush = alt.selection_interval(name='brush')  # selection of type \"interval\"\n",
    "\n",
    "chart = alt.Chart(df).mark_point().encode(\n",
    "    x=alt.X('Beak Length (mm):Q', scale=alt.Scale(zero=False)),\n",
    "    y=alt.Y('Beak Depth (mm):Q', scale=alt.Scale(zero=False)),\n",
    "    color=alt.condition(brush, 'Species:N', alt.value('lightgray'))\n",
    ").properties(\n",
    "    width=300,\n",
    "    height=300\n",
    ").add_params(\n",
    "    brush\n",
    ")\n",
    "\n",
    "vega_pane = pn.pane.Vega(chart, debounce=10)\n",
    "\n",
    "def filtered_table(selection):\n",
    "    if not selection:\n",
    "        return df.iloc[:0]\n",
    "    query = ' & '.join(\n",
    "        f'{crange[0]:.3f} <= `{col}` <= {crange[1]:.3f}'\n",
    "        for col, crange in selection.items()\n",
    "    )\n",
    "    return df.query(query)\n",
    "\n",
    "pn.Column(\n",
    "    'Select points on the plot and watch the linked table update.',\n",
    "    sizing_mode='stretch_width'\n",
    ").servable()\n",
    "\n",
    "pn.Row(\n",
    "    vega_pane,\n",
    "    pn.Column(\n",
    "        pn.pane.DataFrame(\n",
    "            pn.bind(filtered_table, vega_pane.selection.param.brush)\n",
    "        ),\n",
    "        height=350\n",
    "    )\n",
    ").servable()"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
